import { Injectable } from '@nestjs/common';

import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { CommonException } from '../../core/exception/common.exception';
import { SysUser } from './entities/sys-user.entity';
import { CreateSysUserDto } from './dto/create-sys-user.dto';
import { UpdateSysUserDto } from './dto/update-sys-user.dto';
import { SysDeptService } from '../sys-dept/sys-dept.service';

@Injectable()
export class SysUserService {
  constructor(
    @InjectRepository(SysUser)
    private readonly sysUserRepository: Repository<SysUser>,
    private readonly sysDeptService: SysDeptService,
  ) {}

  // 检测两个密码是否一致
  async checkPassword(username: string, password: string) {
    const user = await this.sysUserRepository.findOne({
      where: { user_name: username },
    });
    if (!user) {
      throw new CommonException(500, '用户不存在/密码错误');
    }
    // 判断密码相同
    if (!bcrypt.compareSync(password, user.password)) {
      throw new CommonException(500, '用户不存在/密码错误');
    }
    return user;
  }

  // 获取当前登录用户
  async getCurrentUser(userId: any): Promise<any> {
    const user = await this.sysUserRepository
      .createQueryBuilder('user')
      .leftJoinAndSelect('user.roles', 'roles')
      .where('user.user_id = :userId', { userId })
      .getOne();
    console.log('==user==', user);
    user['dept'] = await this.sysDeptService.findById(user.dept_id);
    return user;
  }

  // 获取用户角色
  async getUserRoles(userId: number): Promise<any> {
    return await this.sysUserRepository
      .createQueryBuilder('user')
      .leftJoinAndSelect('user.roles', 'roles')
      .where('user.user_id = :userId', { userId })
      .getOne();
  }
  // 更新下角色用户
  async updateCurrentUser(userId: number, updateSysUserDto: UpdateSysUserDto) {
    return await this.sysUserRepository.update(userId, updateSysUserDto);
  }

  create(createSysuserDto: CreateSysUserDto) {
    return 'This action adds a new sysuser';
  }

  findAll() {
    return `This action returns all sysuser`;
  }

  findOne(id: number) {
    return `This action returns a #${id} sysuser`;
  }

  update(id: number, updateSysuserDto: UpdateSysUserDto) {
    return `This action updates a #${id} sysuser`;
  }

  remove(id: number) {
    return `This action removes a #${id} sysuser`;
  }
}
